package com.wsoft.core.filter;

import com.wsoft.core.exception.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.wsoft.core.utils.JwtTokenUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能描述
 *
 * @author: juiet
 * @date: 2022年05月30日 10:53
 */

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(this.tokenHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            String username ;

            //调试用token
            String testToken = "eqJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE3MjUzNjA3NjkwNTQsImV4cCI6MTcyNTM5Njc2OX0.EmQa11EmHSo3J1yMB6OkrhtMP7oaLU79VpSHVNtCXpOn8F32Niauq57DZzjIVIkxmmzf_4ndUnpbZTgyP3j7Sw";
            if(authToken.equals(testToken)){
                username = "admin";
            }else{
                username = jwtTokenUtil.getUserNameFromToken(authToken);
            }

            LOGGER.info("checking username:{}", username);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                try {
                    //调试用token
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                    if (authToken.equals(testToken) || jwtTokenUtil.validateToken(authToken, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        LOGGER.info("authenticated user:{}", username);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                } catch (ApiException e) {
                    // 异常捕获，发送到loginStateException
                    request.setAttribute("loginStateException", e);
                    //将异常分发到/loginStateException
                    request.getRequestDispatcher("/loginStateException").forward(request, response);
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }
}
